package com.mr.sell.controller;

import com.mr.sell.entity.ProductCategory;
import com.mr.sell.exception.CustomException;
import com.mr.sell.form.CategoryFrom;
import com.mr.sell.service.CategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * Class: SellerCategoryController
 * User (作者):MRui
 * TODO (描述)：卖家类目Controller
 * Date 2018.10.01 23:28
 */
@RestController
@RequestMapping("/seller/category")
public class SellerCategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
    * User (作者): MRui
    * TODO (描述)：类目list
    * Data：2018.10.01 23:36
    */
    @GetMapping("/list")
    public ModelAndView list(Map<String,Object> map){

        List<ProductCategory> productCategoryList = categoryService.getAll();
        map.put("categoryList",productCategoryList);
        return new ModelAndView("category/list",map);
    }
    /**
    * User (作者): MRui
    * TODO (描述)：类目修改
    * Data：2018.10.01 23:36
    */
    @GetMapping("/index")
    public ModelAndView index(@RequestParam(value = "categoryId",required = false) Integer categoryId,
                              Map<String,Object> map){
        if (!StringUtils.isEmpty(categoryId)){
            ProductCategory productCategory = categoryService.getOne(categoryId);
            map.put("productCategory",productCategory);
        }
        return new ModelAndView("category/index",map);
    }
    /**
    * User (作者): MRui
    * TODO (描述)：类目保存修改
    * Data：2018.10.01 23:59
    */
    @PostMapping("/save")
    public ModelAndView save(@Valid CategoryFrom from,
                              BindingResult bindingResult,
                              Map<String,Object> map){

        if (bindingResult.hasErrors()){
            map.put("msg",bindingResult.getFieldError().getDefaultMessage());
            map.put("url","/sell/seller/category/list");
            return new ModelAndView("common/error",map);
        }
        try {
            ProductCategory productCategory = new ProductCategory();
            if (from.getCategoryId() != 0){
                productCategory = categoryService.getOne(from.getCategoryId());
            }
            BeanUtils.copyProperties(from,productCategory);
            categoryService.save(productCategory);
        }catch (CustomException e){
            map.put("msg",e.getMessage());
            map.put("url","/sell/seller/category/index");
            return new ModelAndView("common/error",map);
        }
        map.put("url","/sell/seller/category/list");
        return new ModelAndView("common/success",map);
    }
}
